package com.spzx.auth.controller;

import com.spzx.auth.form.LoginBody;
import com.spzx.auth.form.RegisterBody;
import com.spzx.auth.service.H5Service;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.utils.JwtUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.auth.AuthUtil;
import com.spzx.common.security.service.TokenService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName H5Controller
 * @Author 波
 * @Date 2024/8/9 19:04
 */
@Slf4j
@RestController
@RequestMapping("/h5")
@Tag(name = "手机端接口")
public class H5Controller extends BaseController {

    @Autowired
    private H5Service h5Service;
    @Autowired
    private TokenService tokenService;
    @Operation(summary = "注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody registerBody){
        h5Service.register(registerBody);
        return success();
    }
    @Operation(summary = "登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody){
        LoginUser loginUser=h5Service.login(loginBody.getUsername(),loginBody.getPassword());
        return success(tokenService.createToken(loginUser));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            //sysLoginService.logout(username);
        }
        return R.ok();
    }

}
